//
//  PersonalViewController.m
//  Contractor
//
//  Created by star j on 16/4/18.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "PersonalViewController.h"
#import "ModelPersonal.h"
#import "AFHTTPRequestOperationManager.h"
#import "CodeWithDES.h"
#import "CONST.h"
#import "PersonalListCell.h"
#import "LoginViewController.h"
#import "MBProgressHUD.h"
//推荐
#import "RecommendViewController.h"
//通知
#import "NotificationViewController.h"
//关于
#import "AboutViewController.h"
//施工
#import "ConstructionViewController.h"
//详情
#import "DetailPersonalViewController.h"
//设置
#import "reviseViewController.h"

@interface PersonalViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    ModelPersonal *personal_model ;
    UIImageView *headBackView ;
    UIButton *headBtn ;
    UITableView *PersonalListView ;
    UIView *btnBackView ;
    RecommendViewController *recommendVC ;
    NotificationViewController *notificationVC ;
    ConstructionViewController *constructionVC ;
    AboutViewController *aboutVC ;
    NSString *rzStr ;
    NSInteger bindingStr ;
    UILabel *RZLabel ;
    UILabel *bindingLabel ;
    UILabel *nameLabel ;
}
@end

@implementation PersonalViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor grayColor] ;
//    //创建个人信息栏
//    [self createPersonalPic] ;
//    //创建TableView
//    [self createTableView] ;
//    //创建退出按钮
//    [self createLogoutBtn] ;

}

- (void)viewWillAppear:(BOOL)animated
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //创建个人信息栏
        [self createPersonalPic] ;
        //创建TableView
        [self createTableView] ;
        //创建退出按钮
        [self createLogoutBtn] ;
    }) ;
    
    //隐藏导航栏
    self.navigationController.navigationBarHidden = YES ;

    personal_model = [[ModelPersonal alloc] init] ;
    [self userRz] ;
    [self userBinding] ;
    [self downloadPersonalDate] ;
}


#pragma mark - 加载数据
- (void)downloadPersonalDate
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"正在努力加载", @"HUD loading title") ;
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:8] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *parameters = @{@"cmd":cmd,@"uid":uid};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        [hud hideAnimated:YES] ;
        //解密并解析json数据，将json转成字典
        NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
        NSLog(@"decodeStr:%@",decodeStr) ;
        decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr1:%@",decodeStr) ;
        NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
        id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
        //获取字典中的值
        if ([result isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *dic = result ;
           // NSLog(@"dic:%@",dic) ;
            if (([dic[@"status"] integerValue] == 1) && ![dic[@"content"] isKindOfClass:[NSNull class]])
            {
                for (NSDictionary *content in dic[@"content"])
                {
                    [personal_model setValuesForKeysWithDictionary:content] ;
                    NSLog(@"realname:%@",personal_model.realname) ;
                    [self createNameLabel] ;
                }
            }
            
        }
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        [hud hideAnimated:YES] ;
        NSLog(@"Error: %@", error);
    }];
}

- (void)userRz
{
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:304] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *parameters = @{@"cmd":cmd,@"uid":uid};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"rzStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             // NSLog(@"dic:%@",dic) ;
             if ([dic[@"status"] integerValue] == 1)
             {
                 rzStr = dic[@"userrz"] ;
                 [self createRZLabel] ;
                 NSLog(@"dicRZ:%@",dic) ;
             }
             
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
     }];
}

- (void)userBinding
{
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
   
    NSNumber *cmd = [[NSNumber alloc] initWithInt:305] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    NSDictionary *parameters = @{@"cmd":cmd,@"uid":uid};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"bindingStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             // NSLog(@"dic:%@",dic) ;
             if ([dic[@"status"] integerValue] == 1)
             {
                 bindingStr = [dic[@"userbinding"] integerValue] ;
                 [self createBindingLabel] ;
             }
             
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
     }];
}

#pragma mark - 创建个人信息栏
- (void)createPersonalPic
{
    [headBackView removeFromSuperview] ;
    
    //状态栏背景图
    UIImage *backImage = [UIImage imageNamed:@"personalBg.png"] ;
    float height = __kScreenWidth * backImage.size.height/backImage.size.width ;
    headBackView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, __kScreenWidth, height+20)] ;
    [headBackView setImage:backImage] ;
    headBackView.userInteractionEnabled = YES ;
    [self.view addSubview:headBackView] ;
    
    //状态栏头像
    float btnSize = __kScreenWidth / 4 ;
    headBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    headBtn.frame = CGRectMake((__kScreenWidth - btnSize) / 2, (height +20 - btnSize) / 2-10, btnSize, btnSize) ;
    headBtn.layer.masksToBounds = YES ;
    headBtn.layer.cornerRadius = btnSize / 2 ;
    [headBtn setImage:[UIImage imageNamed:@"default_user_icon.png"] forState:UIControlStateNormal] ;
    [headBtn addTarget:self action:@selector(userInfo) forControlEvents:UIControlEventTouchUpInside] ;
    [headBackView addSubview:headBtn] ;
    
    UIButton *setBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [setBtn setImage:[UIImage imageNamed:@"title_setting_btn_normal_icon.png"] forState:UIControlStateNormal] ;
    setBtn.frame = CGRectMake(__kScreenWidth - 50, 10, 50, 50) ;
    [setBtn setContentMode:UIViewContentModeCenter];
    [setBtn setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];

    
    [setBtn addTarget:self action:@selector(Btnset) forControlEvents:UIControlEventTouchUpInside] ;
    [headBackView addSubview:setBtn] ;
    

}

- (void)Btnset
{
    NSString *livestr = [NSString stringWithFormat:@"%@ %@ %@ %@",personal_model.liveLocation1,personal_model.liveLocation2,personal_model.liveLocation3,personal_model.liveaddress] ;
    reviseViewController *setVC = [[reviseViewController alloc] init] ;
    setVC.RzStr = personal_model.renzheng ;
    setVC.addressStr = livestr ;
    setVC.model = personal_model ;
    self.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:setVC animated:NO] ;
    self.hidesBottomBarWhenPushed = NO ;
}

- (void)userInfo
{
    DetailPersonalViewController *detailVC = [[DetailPersonalViewController alloc] init] ;
    
    self.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:detailVC animated:NO] ;
    self.hidesBottomBarWhenPushed = NO ;
}

#pragma mark - 创建退出按钮
- (void)createLogoutBtn
{
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    //btn背景
    float backViewY = PersonalListView.frame.origin.y + PersonalListView.frame.size.height + 10 ;
    float backViewHeight = __kScreenHeight - backViewY - 44;
    
    [btnBackView removeFromSuperview] ;
    
    btnBackView = [[UIView alloc] initWithFrame:CGRectMake(0, backViewY, __kScreenWidth, backViewHeight)] ;
    btnBackView.backgroundColor = [UIColor whiteColor] ;
    [self.view addSubview:btnBackView] ;
    
    //创建退出按钮
    //float btnY = (backViewHeight - 50) / 2 ;
    UIButton *logoutBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    logoutBtn.frame = CGRectMake(20, (backViewHeight - 40) * 0.618, __kScreenWidth - 40, 40) ;
    [logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal] ;
    logoutBtn.backgroundColor = [UIColor blueColor] ;
    logoutBtn.layer.cornerRadius = 10.0f ;
    [logoutBtn addTarget:self action:@selector(Logout) forControlEvents:UIControlEventTouchUpInside] ;
    [btnBackView addSubview:logoutBtn] ;
}

//退出登录
- (void)Logout
{
//    NSLog(@"退出") ;
//    UIAlertController *logoutAlter = [UIAlertController alertControllerWithTitle:@"是否退出登录？" message:nil preferredStyle:UIAlertControllerStyleAlert] ;
//    
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"取消") ;
//    }] ;
//    
//    UIAlertAction *logoutAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"确认") ;
//    }] ;
//    
//    [logoutAlter addAction:cancelAction] ;
//    [logoutAlter addAction:logoutAction] ;
//    [self presentViewController:logoutAlter animated:YES completion:nil] ;
    
    UIAlertView *logoutAlter = [[UIAlertView alloc] initWithTitle:@"是否退出登录？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil] ;
    logoutAlter.frame = CGRectMake((__kScreenWidth-150)/2, (__kScreenHeight-100)/2, 150, 100) ;
    [logoutAlter show] ;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        LoginViewController *vc = [[LoginViewController alloc]init] ;
        self.hidesBottomBarWhenPushed = YES ;
        [self.navigationController pushViewController:vc animated:NO] ;
        
        //[self presentViewController:vc animated:YES completion:nil] ;
        NSLog(@"确认") ;
    }
}

#pragma mark - 创建名字label
- (void)createNameLabel
{
    //姓名
    NSLog(@"realname2:%@",personal_model.realname) ;
    
    [nameLabel removeFromSuperview] ;
    nameLabel = [[UILabel alloc] init] ;
    float labelY = headBtn.frame.origin.y + __kScreenWidth / 4 + 10 ;
    
    nameLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
    nameLabel.backgroundColor = [UIColor clearColor] ;
    NSString *gender = nil ;
    if (personal_model.gender == 1) {
        gender = @"男" ;
    }
    else
    {
        gender = @"女" ;
    }
    nameLabel.text = [NSString stringWithFormat:@"%@  %@",personal_model.realname,gender] ;
    CGSize nameSize = [self lengthwithLabel:nameLabel withsize:14.0f] ;
    nameLabel.frame = CGRectMake((__kScreenWidth - nameSize.width)/2, labelY, nameSize.width, 16.0f) ;
    [headBackView addSubview:nameLabel] ;
    
}

- (void)createRZLabel
{
    [RZLabel removeFromSuperview] ;
    
    RZLabel = [[UILabel alloc] init] ;
    float labelY = headBtn.frame.origin.y + __kScreenWidth / 4 + 10 ;
    
    RZLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:15.0f] ;
    RZLabel.backgroundColor = [UIColor clearColor] ;
    NSString *RZ = nil ;
    if ([rzStr isEqualToString:@"1"]) {
        RZ = @"已认证" ;
        RZLabel.textColor = [UIColor redColor] ;
    }
    else
    {
        RZ = @"未认证" ;
        RZLabel.textColor = [UIColor lightGrayColor] ;
    }
    RZLabel.text = [NSString stringWithFormat:@"%@",RZ] ;
    CGSize bindingSize = [self lengthwithLabel:RZLabel withsize:15.0f] ;
    RZLabel.frame = CGRectMake(__kScreenWidth - bindingSize.width - 65, labelY, bindingSize.width, 16.0f) ;
    [headBackView addSubview:RZLabel] ;
}


- (void)createBindingLabel
{
    [bindingLabel removeFromSuperview] ;
    bindingLabel = [[UILabel alloc] init] ;
    float labelY = headBtn.frame.origin.y + __kScreenWidth / 4 + 10 ;
    
    bindingLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:15.0f] ;
    bindingLabel.backgroundColor = [UIColor clearColor] ;
    NSString *binding = nil ;
    if (bindingStr == 1) {
        binding = @"已绑定" ;
        bindingLabel.textColor = [UIColor redColor] ;
    }
    else
    {
        binding = @"未绑定" ;
        bindingLabel.textColor = [UIColor lightGrayColor] ;
    }
    bindingLabel.text = [NSString stringWithFormat:@"%@",binding] ;
    CGSize bindingSize = [self lengthwithLabel:bindingLabel withsize:15.0f] ;
    bindingLabel.frame = CGRectMake(__kScreenWidth - bindingSize.width - 10, labelY, bindingSize.width, 16.0f) ;
    [headBackView addSubview:bindingLabel] ;
}

- (CGSize)lengthwithLabel:(UILabel *)lable withsize:(CGFloat) size
{
    NSDictionary *attribute1 = @{NSFontAttributeName: [UIFont fontWithName:@"AvenirLTStd-Light" size:size]};
    CGSize DescSize = [lable.text boundingRectWithSize:CGSizeMake(MAXFLOAT, size) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute1 context:nil].size;
    return DescSize ;
}


#pragma mark - 创建tableview
- (void)createTableView ;
{
    [PersonalListView removeFromSuperview] ;
    
    PersonalListView = [[UITableView alloc] initWithFrame:CGRectMake(0,  headBackView.frame.size.height + 10, __kScreenWidth, 199.5) style:UITableViewStylePlain] ;
    PersonalListView.separatorStyle = UITableViewCellSeparatorStyleSingleLine ;
    PersonalListView.showsVerticalScrollIndicator = NO;
    PersonalListView.scrollEnabled = NO ;
    PersonalListView.delegate = self ;
    PersonalListView.dataSource = self ;
    [self.view addSubview:PersonalListView] ;
    
    //初始化controller
    recommendVC = [[RecommendViewController alloc] init] ;
    notificationVC = [[NotificationViewController alloc] init] ;
    constructionVC = [[ConstructionViewController alloc] init] ;
    aboutVC = [[AboutViewController alloc] init] ;
}

#pragma mark - TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PersonalListCell *cell = [PersonalListCell cellWithTableView:tableView] ;
    cell.selectionStyle = UITableViewCellSelectionStyleNone ;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator ;
    NSArray *titleArray = @[@"推荐享优惠",@"我的通知",@"施工标准",@"关于包工婆"] ;
    UIImage *image1 = [UIImage imageNamed:@"recommend.png"] ;
    UIImage *image2 = [UIImage imageNamed:@"notification.png"] ;
    UIImage *image3 = [UIImage imageNamed:@"construction.png"] ;
    UIImage *image4 = [UIImage imageNamed:@"about.png"] ;
    NSArray *imageArray = @[image1,image2,image3,image4] ;
    [cell configTitle:titleArray[indexPath.row] configImage:imageArray[indexPath.row]] ;
    if (indexPath.row == 0) {
        [cell.barcodeView setImage:[UIImage imageNamed:@"recommend_barcode"]] ;
    }
    return cell ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50 ;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            self.hidesBottomBarWhenPushed = YES ;
            recommendVC.model = personal_model ;
            [self.navigationController pushViewController:recommendVC animated:NO] ;
            self.hidesBottomBarWhenPushed = NO ;
             break;
        case 1:
            self.hidesBottomBarWhenPushed = YES ;
            [self.navigationController pushViewController:notificationVC animated:NO] ;
            self.hidesBottomBarWhenPushed = NO ;
            break;
        case 2:
            self.hidesBottomBarWhenPushed = YES ;
            [self.navigationController pushViewController:constructionVC animated:NO] ;
            self.hidesBottomBarWhenPushed = NO ;
            break;
        case 3:
            self.hidesBottomBarWhenPushed = YES ;
            [self.navigationController pushViewController:aboutVC animated:NO] ;
            self.hidesBottomBarWhenPushed = NO ;
            break;
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
